package com.yeqian.entity;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import lombok.Data;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Data
@JsonPropertyOrder({"code", "message", "data"})
public class ResultJson {
    private Object data;
    private Integer code;
    private String message;

    public static ResultJson Success(String mesages) {
        ResultJson resultJson = new ResultJson();
        resultJson.setCode(200);
        resultJson.setMessage(mesages);
        return resultJson;
    }

    public static ResultJson Success(String mesages, Object data) {
        ResultJson resultJson = new ResultJson();
        resultJson.setCode(200);
        resultJson.setData(data);
        resultJson.setMessage(mesages);
        return resultJson;
    }

    public static ResultJson error(Integer code, String mesages) {
        ResultJson resultJson = new ResultJson();
        resultJson.setCode(code);
        resultJson.setMessage(mesages);
        return resultJson;
    }

    public static void writeJSON(
            HttpServletResponse response,
            Object data) throws IOException {
        response.setContentType("application/json; charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Method", "POST,GET");
        // 输出JSON
        PrintWriter out = response.getWriter();
        String JsonString = new ObjectMapper().registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule()).writeValueAsString(data);
        out.write(JsonString);
        out.flush();
        out.close();
    }
}
